<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>Layui</title>
  <meta name="renderer" content="webkit">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <link rel="stylesheet" href="../../layui/css/layui.css" media="all">
  <!-- 注意：如果你直接复制所有代码到本地，上述css路径需要改成你本地的 -->
  <script src="../../js/common.js"></script>
  <style>
    .search-style {
      margin-left: 5%;
    }
  </style>
</head>

<body>
  <div style="margin: 20px;"></div>
  <form class="layui-form" action="">
    <!-- 输入框内容 -->
    <div class="demoTable search-style">
      手机号：
      <div class="layui-inline">
        <input class="layui-input" name="id" id="searchByPhone" autocomplete="off">
      </div>
      &nbsp;&nbsp;&nbsp;&nbsp;
      邮箱：
      <div class="layui-inline">
        <input class="layui-input" name="id" id="searchByEmail" autocomplete="off">
      </div>
      <a class="layui-btn1 layui-btn" lay-submit lay-filter="formDemo">搜索</a>
      <a class="layui-btn2 layui-btn" lay-submit lay-filter="formDemo">清空</a>
    </div>
  </form>

  <table class="layui-hide" id="test" lay-filter="test" lay-data="{id: 'idTest'}"></table>

  <!-- 工具栏模板： -->
  <script type="text/html" id="toolbarDemo">
      <div class="layui-btn-container">
        <button class="layui-btn layui-btn-sm" lay-event="delete">批量删除</button>
        <button class="layui-btn layui-btn-sm" lay-event="update">编辑</button>
      </div>

      <script type="text/html" id="barDemo">
        <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="detail">权限修改</a>
        <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="delete" style="background-color:#FF5511;">
          <font color="FFFFFF">删除</font>
        </a>
    </script>



  <!-- 显示序号 -->
  <script type="text/html" id="titleTpl">
    {{d.LAY_TABLE_INDEX+1}}
  </script>


  <!-- 注意：如果你直接复制所有代码到本地，上述 JS 路径需要改成你本地的 -->
  <script src="../../layui/layui.js" charset="utf-8"></script>
  <script type="text/javascript">

    layui.use('table', function () {
      //得到各种内置组件
      var layer = layui.layer //弹层
        ,
        laypage = layui.laypage //分页
        ,
        laydate = layui.laydate //日期
        ,
        table = layui.table //表格
        ,
        carousel = layui.carousel //轮播
        ,
        upload = layui.upload //上传
        ,
        element = layui.element //元素操作
        ,
        slider = layui.slider //滑块
        ,
        dropdown = layui.dropdown //下拉菜单
        ,
        $ = layui.$

      var table = layui.table;
      let curr;
      let limit;
      var tableIns = table.render({
        elem: '#test',
        id: 'testReload',
        url: "/api/READ/api/my/user/admin/info",
        headers: {
          token: localStorage.token
        },
        cellMinWidth: 80, //全局定义常规单元格的最小宽度，layui 2.2.1 新增,
        height: 'full-80',//高度最大化减去差值 ,
        toolbar: '#toolbarDemo',
        page: true, //开启分页
        limit: 10,
        limits: [10, 15, 40, 60],
        request: {
          //这里设置的pageNum与pageSize每次请求时都会传给后端，从而实现layui的自定义分页
          pageName: 'current', //页码的参数名称，默认：page
          limitName: 'pageSize', //每页数据量的参数名，默认：limit
        },
        parseData: function (res) { //res 即为原始返回的数据
          //console.log(res);
          return {
            "code": res.code, //解析接口状态
            "msg": res.msg, //解析提示文本
            "data": res.data, //解析数据列表
            "count": res.total //总共条数
          };

        },
        response: {
          statusCode: 200 //规定成功的状态码，默认：0
        },

        cols: [
          [{
            type: 'checkbox',
            fixed: 'left'
          },
          {
            field: 'id',
            title: '用户ID',
            width: '5%',
            fixed: 'left',
            align: 'center',
            templet: '#titleTpl'
          },
          {
            field: 'uid',
            width: '8%',
            title: 'ID',
            align: 'center',
            hide: true
          }, {
            field: 'nickName',
            width: '10%',
            align: 'center',
            title: '昵称'
          }, {
            field: 'userName',
            width: '10%',
            align: 'center',
            title: '账号'
          }, {
            field: 'phone',
            title: '手机号',
            width: '10%',
            align: 'center',
            minWidth: 100
          } //minWidth：局部定义当前单元格的最小宽度，layui 2.2.1 新增
            , {
            field: 'email',
            title: '邮箱',
            width: '15%',
            align: 'center',
          }, {
            field: 'loginTime',
            align: 'center',
            width: '11%',
            title: '登录时间',
            sort: true
          },{
            title: '状态',
            width: '6.5%',
            align: 'center',
            templet: function (d) {
              // console.log(d);
              if (d.status == 0) {
                var state = "<input type='checkbox' disabled='disabled' name='state' checked='' value='" + d.uid +
                  "' id='status' lay-filter='status' lay-skin='switch' lay-text='正常|违规'>";
              } else {
                var state = "<input type='checkbox' disabled='disabled' name='state' value='" + d.uid +
                  "' id='status' lay-filter='status' lay-skin='switch' lay-text='正常|违规'>";
              }
              return state;
            },
          }, {
            fixed: 'right',
            width: '10%',
            align: 'center',
            toolbar: '#barDemo'
          }

          ]
        ],
        done: function (res) {
          //如果是异步请求数据方式，res即为你接口返回的信息。
          //如果是直接赋值的方式，res即为：{data: [], count: 99} data为当前页数据、count为数据总长度
          // console.log(res);
        }
      });

      /*
          清除搜索框内容
      */
      $('.demoTable .layui-btn2').on('click', function () {
        $('#searchByPhone')[0].value = '';
        $('#searchByEmail')[0].value = '';
      });

      /**
      *   搜索按钮 
      */
      $('.demoTable .layui-btn1').on('click', function () {
        var searchByPhoneValue = $('#searchByPhone')[0].value.replace(/\s*/g, "");
        var searchByEmailValue = $('#searchByEmail')[0].value.replace(/\s*/g, "");
        var condition;

        if (searchByPhoneValue.length != 0 && searchByEmailValue.length != 0) {
          layer.msg('只查询一个条件');
          return;
        }

        tableIns.reload({
          page: {
            curr: 1, //重新从第 1 页开始
          },
          method: 'get',
          contentType: "application/x-www-form-urlencoded",
          where: {
            phone: searchByPhoneValue,
            email: searchByEmailValue
          },
          parseData: function (res) { //res 即为原始返回的数据
            //console.log(res);
            return {
              "code": res.code, //解析接口状态
              "msg": res.msg, //解析提示文本
              "data": res.data, //解析数据列表
              "count": res.total //总共条数
            }
          },
        });
      });

      // switch开关  改变用户状态
      let form = layui.form;
      form.on('switch(status)', function (data) {
        // console.log(data.value)
        var flag = this.checked;
        var checked = this.checked;
        var uid = data.value;
        layer.msg('是否处理', {
          time: 5000, //5s后自动关闭
          btn: ['确定', '取消'],
          yes: function (index) {
            //TODO 此时进行ajax的服务器访问，如果返回数据正常，则进行后面代码的调用
            $.ajax({
              type: 'put',
              url: '/api/READ/api/my/user/change/status/' + uid,
              headers: {
                token: localStorage.token
              },
              success: function (res) {
                if (res.code === '200') {
                  if (flag) {
                    layer.msg('已启用');
                  } else {
                    layer.msg('已关闭');
                  }
                } else {
                  layer.msg(res.msg);
                  data.elem.checked = !checked;
                  form.render();
                  layer.close(index);
                  //按钮【按钮一】的回调
                }
              }
            })

          },
          btn2: function (index) {
            //按钮【按钮二】的回调
            data.elem.checked = !checked;
            form.render();
            layer.close(index);
            //return false; //开启该代码可禁止点击该按钮关闭
          }
        });
      })

      //监听头工具栏事件
      table.on('toolbar(test)', function (obj) {
        var checkStatus = table.checkStatus(obj.config.id);
        data = checkStatus.data; //获取选中的数据

        switch (obj.event) {
          case 'update':
            if (data.length === 0) {
              layer.msg('请选择一行');
            } else if (data.length > 1) {
              layer.msg('只能同时编辑一个');
            } else {
              layer.alert('编辑 [uid]：' + checkStatus.data[0].uid);
            }
            break;
          case 'delete':
            var dataList = checkStatus.data;
            var len = dataList.length;
            var ids = new Array(len);

            for (var i = 0; i < len; ++i) {
              ids[i] = dataList[i].uid;
            }
            // console.log(ids);

            layer.msg('是否刪除 ' + len + ' 条用户数据', {
              time: 5000, //5s后自动关闭
              btn: ['确定', '取消'],
              yes: function (index) {
                //TODO 此时进行ajax的服务器访问，如果返回数据正常，则进行后面代码的调用
                $.ajax({
                  type: 'delete',
                  url: '/api/READ/api/my/user/deletes',
                  async: false,
                  dataType: "json",
                  headers: {
                    'Content-Type': 'application/json;charset=utf-8',
                    token: localStorage.token
                  }, //接口json格式
                  data: JSON.stringify(ids),
                  success: function (res) {
                    layer.msg(res.msg);
                    layer.close(index);
                    window.location.reload();
                  }

                })

                layer.close(index);
              }
            });
            break;
        };
      });

      //监听行工具事件
      table.on('tool(test)', function (obj) { //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
        var data = obj.data, //获得当前行数据
          layEvent = obj.event,
          uid = data.uid //获得 lay-event 对应的值

        if (layEvent === 'detail') {

          layer.open({
            type: 2, //打开一个iframe
            title: '账号查看&修改',
            content: './update_user.html?uid=' + uid,
            maxmin: true,
            area: ['550px', '500px'],
            btn: ['确定', '取消'],
            yes: function (index, layero) {
              //点击确认触发 iframe 内容中的按钮提交
              layer.close(index);
            }
          });
        } else {
          layer.msg('删除操作');
        }
      });
    });
  </script>

</body>

</html>